package com.seafood.controller;

import com.seafood.dto.ColdChainRecordDTO;
import com.seafood.service.ColdChainRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;

/**
 * 冷链运输记录控制器
 */
@RestController
@RequestMapping("/api/cold-chain/records")
@RequiredArgsConstructor
public class ColdChainRecordController {
    
    private final ColdChainRecordService coldChainRecordService;
    
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    
    // 创建冷链运输记录
    @PostMapping
    public ResponseEntity<ColdChainRecordDTO> createRecord(@Valid @RequestBody ColdChainRecordDTO recordDTO) {
        ColdChainRecordDTO created = coldChainRecordService.createColdChainRecord(recordDTO);
        return ResponseEntity.ok(created);
    }
    
    // 更新冷链运输记录
    @PutMapping("/{id}")
    public ResponseEntity<ColdChainRecordDTO> updateRecord(
            @PathVariable Long id,
            @Valid @RequestBody ColdChainRecordDTO recordDTO) {
        ColdChainRecordDTO updated = coldChainRecordService.updateColdChainRecord(id, recordDTO);
        return ResponseEntity.ok(updated);
    }
    
    // 根据ID获取冷链记录
    @GetMapping("/{id}")
    public ResponseEntity<ColdChainRecordDTO> getRecord(@PathVariable Long id) {
        ColdChainRecordDTO record = coldChainRecordService.getColdChainRecordById(id);
        return ResponseEntity.ok(record);
    }
    
    // 根据运输单号获取冷链记录
    @GetMapping("/by-transport-number/{transportNumber}")
    public ResponseEntity<ColdChainRecordDTO> getRecordByTransportNumber(
            @PathVariable String transportNumber) {
        ColdChainRecordDTO record = coldChainRecordService.getColdChainRecordByTransportNumber(transportNumber);
        return ResponseEntity.ok(record);
    }
    
    // 根据订单ID获取冷链记录列表
    @GetMapping("/by-order/{orderId}")
    public ResponseEntity<List<ColdChainRecordDTO>> getRecordsByOrderId(@PathVariable Long orderId) {
        List<ColdChainRecordDTO> records = coldChainRecordService.getColdChainRecordsByOrderId(orderId);
        return ResponseEntity.ok(records);
    }
    
    // 根据产品ID获取冷链记录列表
    @GetMapping("/by-product/{productId}")
    public ResponseEntity<List<ColdChainRecordDTO>> getRecordsByProductId(@PathVariable Long productId) {
        List<ColdChainRecordDTO> records = coldChainRecordService.getColdChainRecordsByProductId(productId);
        return ResponseEntity.ok(records);
    }
    
    // 分页获取冷链记录
    @GetMapping
    public ResponseEntity<Page<ColdChainRecordDTO>> getRecords(
            @PageableDefault(size = 20) Pageable pageable) {
        Page<ColdChainRecordDTO> records = coldChainRecordService.getColdChainRecords(pageable);
        return ResponseEntity.ok(records);
    }
    
    // 根据状态分页获取冷链记录
    @GetMapping("/by-status/{status}")
    public ResponseEntity<Page<ColdChainRecordDTO>> getRecordsByStatus(
            @PathVariable String status,
            @PageableDefault(size = 20) Pageable pageable) {
        Page<ColdChainRecordDTO> records = coldChainRecordService.getColdChainRecordsByStatus(status, pageable);
        return ResponseEntity.ok(records);
    }
    
    // 获取正在运输中的记录
    @GetMapping("/active")
    public ResponseEntity<List<ColdChainRecordDTO>> getActiveTransports() {
        List<ColdChainRecordDTO> records = coldChainRecordService.getActiveTransports();
        return ResponseEntity.ok(records);
    }
    
    // 根据运输公司搜索记录
    @GetMapping("/search")
    public ResponseEntity<Page<ColdChainRecordDTO>> searchByTransportCompany(
            @RequestParam String transportCompany,
            @PageableDefault(size = 20) Pageable pageable) {
        Page<ColdChainRecordDTO> records = coldChainRecordService.searchByTransportCompany(transportCompany, pageable);
        return ResponseEntity.ok(records);
    }
    
    // 根据时间范围查找记录
    @GetMapping("/by-time-range")
    public ResponseEntity<List<ColdChainRecordDTO>> getRecordsByTimeRange(
            @RequestParam String startTime,
            @RequestParam String endTime) {
        LocalDateTime start = LocalDateTime.parse(startTime, FORMATTER);
        LocalDateTime end = LocalDateTime.parse(endTime, FORMATTER);
        List<ColdChainRecordDTO> records = coldChainRecordService.getColdChainRecordsByTimeRange(start, end);
        return ResponseEntity.ok(records);
    }
    
    //(
    public ResponseEntity<List<ColdChainRecordDTO>> getRecordsWithActiveAlerts() {
        List<ColdChainRecordDTO> records = coldChainRecordService.getRecordsWithActiveAlerts();
        return ResponseEntity.ok(records);
    }
    
    //(
    public ResponseEntity<Page<ColdChainRecordDTO>> getRecordsByQualityScoreRange(
            @RequestParam Double minScore,
            @RequestParam Double maxScore,
            @PageableDefault(size = 20) Pageable pageable) {
        Page<ColdChainRecordDTO> records = coldChainRecordService.getColdChainRecordsByQualityScoreRange(minScore, maxScore, pageable);
        return ResponseEntity.ok(records);
    }
    
    //(
    public ResponseEntity<ColdChainRecordDTO> startTransport(@PathVariable Long id) {
        ColdChainRecordDTO record = coldChainRecordService.startTransport(id);
        return ResponseEntity.ok(record);
    }
    
    //(
    public ResponseEntity<ColdChainRecordDTO> completeTransport(@PathVariable Long id) {
        ColdChainRecordDTO record = coldChainRecordService.completeTransport(id);
        return ResponseEntity.ok(record);
    }
    
    //(
    public ResponseEntity<ColdChainRecordDTO> cancelTransport(
            @PathVariable Long id,
            @RequestParam String reason) {
        ColdChainRecordDTO record = coldChainRecordService.cancelTransport(id, reason);
        return ResponseEntity.ok(record);
    }
    
    //(
    public ResponseEntity<ColdChainRecordDTO> updateCurrentStatus(
            @PathVariable Long id,
            @RequestParam(required = false) String location,
            @RequestParam(required = false) Double currentTemp,
            @RequestParam(required = false) Double currentHumidity,
            @RequestParam(required = false) String gpsCoordinates) {
        ColdChainRecordDTO record = coldChainRecordService.updateCurrentStatus(id, location, currentTemp, currentHumidity, gpsCoordinates);
        return ResponseEntity.ok(record);
    }
    
    //(
    public ResponseEntity<Double> calculateQualityScore(@PathVariable Long id) {
        Double score = coldChainRecordService.calculateQualityScore(id);
        return ResponseEntity.ok(score);
    }
    
    //(
    public ResponseEntity<Map<String, Object>> getTransportStatistics() {
        Map<String, Object> statistics = coldChainRecordService.getTransportStatistics();
        return ResponseEntity.ok(statistics);
    }
    
    //(
    public ResponseEntity<Map<String, Object>> generateTransportReport(@PathVariable Long id) {
        Map<String, Object> report = coldChainRecordService.generateTransportReport(id);
        return ResponseEntity.ok(report);
    }
    
    //(
    public ResponseEntity<Void> deleteRecord(@PathVariable Long id) {
        coldChainRecordService.deleteColdChainRecord(id);
        return ResponseEntity.ok().build();
    }
}